import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

const useTodoListStore = defineStore(
  'todoList',
  () => {
    // 创建数据源
    const datas = ref([])
    // 保存待办事项
    const sent = (content) => {
      // console.log('~~~~~~~~~~~')
      datas.value.push({ id: Date.now(), isChecked: false, content: content })
    }
    // 删除单个待办事项
    const del = (index) => {
      datas.value.splice(index, 1)
    }
    // 全选
    const checkedAll = computed({
      get() {
        return (
          datas.value.every((data) => data.isChecked) && datas.value.length > 0
        )
      },
      set(status) {
        datas.value.forEach((data) => {
          data.isChecked = status
        })
      },
    })
    // 计算已完成的待办事项的个数
    const checkedSelect = computed(() => {
      return datas.value.filter((item) => item.isChecked).length
    })
    // 清除已完成的待办事项
    const delSelect = () => {
      datas.value = datas.value.filter((item) => !item.isChecked)
    }
    return {
      datas,
      sent,
      del,
      checkedAll,
      checkedSelect,
      delSelect,
    }
  },
  {
    persist: true,
  }
)

export default useTodoListStore
